package com.glorystone.ins.controller;

import com.glorystone.ins.beanUtils.BeanUtils;
import com.glorystone.ins.beanUtils.ExcelUtil;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.common.util.DateEnum;
import com.glorystone.ins.common.util.DateUtils;
import com.glorystone.ins.domain.*;
import com.glorystone.ins.enums.CapitalRecordStatusEnum;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.*;
import com.glorystone.ins.vo.RepayingCVo;
import com.glorystone.ins.vo.RepayingIVo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author:LiuSC
 * @Date:Created in 2018-03-19 15:47
 * @since: JDK 1.7
 * @Description:
 */
@Controller
@RequestMapping("/repaying")
public class OrderRepayingController extends BaseController {

    @Autowired
    private OrderReapyingService orderReapyingService;
    @Autowired
    private InsurerService insurerService;
    @Autowired
    private ChannelService channelService;

    @Autowired
    private IDictionaryService iDictionaryService;

    @RequestMapping(value="/tolist/{type}")
    public ModelAndView toInsurerList(ModelAndView mv,@PathVariable String type){
        if(!"C".equals(type)){
            type="I";
        }
        List<Insurer> list = insurerService.selectAllInsurer();
        List<Channel> channels = channelService.findAll();
        List<Dictionary> dlist = iDictionaryService.getDictionaryListByType("PAY_THEME");
        mv.addObject("insurerList",list);
        mv.addObject("channels",channels);
        mv.addObject("dictionary",dlist);
        mv.addObject("type",type);
        mv.setViewName("repaying/repaying");
        return mv;
    }

    @RequestMapping(value="/queryInsurerData",method = RequestMethod.GET)
    @ResponseBody
    public DataTable<Repaying> queryTableData(HttpServletRequest request){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        PageVo vo =  parametToPageVoData(request,Repaying.class,user);
        PageList<Repaying> list = orderReapyingService.queryRepayList(vo);
        DataTable data = resultToDataTable(list);
        return data;
    }

    @RequestMapping(value="/addi",method = RequestMethod.POST)
    public String addIRepaying(@ModelAttribute(value = "form") Repaying repay){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long id = user.getTid();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = repay.getSurrenderDateStart();
        try {
            Date date = sdf.parse(dateString);
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            repay.setSurrenderDate(localDateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        repay.setCapitalUpdateBy(id);
        repay.setCapitalUpdateDate(LocalDateTime.now());
        repay.setCheckDate(LocalDateTime.now());
        repay.setCapitalStatus(CapitalRecordStatusEnum.FOR_COLLECTION.getValue());
        boolean upRp = orderReapyingService.updateCapital(repay);
        return "redirect:/repaying/tolist/I";
    }
    @RequestMapping(value="/addc",method = RequestMethod.POST)
    public String addCRepaying(@ModelAttribute(value = "form") Repaying repay){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long id = user.getTid();
        repay.setCapitalUpdateBy(id);
        repay.setCapitalUpdateDate(LocalDateTime.now());
        repay.setCapitalStatus(CapitalRecordStatusEnum.SETTLED.getValue());
        boolean upRp = orderReapyingService.updateCapital(repay);
        return "redirect:/repaying/tolist/C";
    }
    @RequestMapping("/downloadi")
    public void exportRepayiInfo(HttpServletRequest request, HttpServletResponse response) {
        String capitalStatus = request.getParameter("capitalStatus");
        String insyrerId = request.getParameter("insyrerId");
        String ordNum = request.getParameter("ordNum");
        String channelId = request.getParameter("channelId");
        String dateIssuanceStart = request.getParameter("dateIssuanceStart");
        String dateIssuanceEnd = request.getParameter("dateIssuanceEnd");
        String surrenderDateStart = request.getParameter("surrenderDateStart");
        String surrenderDateEnd = request.getParameter("surrenderDateEnd");
        Map<String,String> map =Maps.newHashMap();
        map.put("capitalStatus",capitalStatus);
        map.put("insyrerId",insyrerId);
        map.put("ordNum",ordNum);
        map.put("channelId",channelId);
        map.put("dateIssuanceStart",dateIssuanceStart);
        map.put("dateIssuanceEnd",dateIssuanceEnd);
        map.put("surrenderDateStart",surrenderDateStart);
        map.put("surrenderDateEnd",surrenderDateEnd);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long userId =user.getTid();
        int level = user.getUserLevel();
        if(3==level){
            map.put("userId",""+userId);
        }
        List<Dictionary> dlist = iDictionaryService.getDictionaryListByType("PAY_THEME");
        List<Repaying> list = orderReapyingService.getRepayList(map);
        List<RepayingIVo> rList = Lists.newArrayList();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        for(Repaying rp:list){
            RepayingIVo rv = new RepayingIVo();
            rv.setOrdNum(rp.getOrdNum());
            for(Dictionary d:dlist){
                if(d.getRiskKey().equals(""+rp.getPaySubject())){
                    rv.setPaySubject(d.getRiskValue());
                }
            }
            rv.setInsyrerName(rp.getInsyrerName());
            if(1==rp.getChannelType()){
                rv.setChannelName(rp.getChannelPName());
            }else{
                rv.setChannelName(rp.getChannelCName());
            }
            rv.setChannelPhone(rp.getChannelPhone());
            if(1==rp.getTypeInsurance()){
                rv.setTypeInsurance("商业险");
            }else{
                rv.setTypeInsurance("交强险");
            }
            rv.setInsurant(rp.getInsurant());
            rv.setOrgIdCode(rp.getOrgIdCode());
            rv.setPlateNum(rp.getPlateNum());
            rv.setMercialPremium(""+rp.getMercialPremium());
            rv.setPulsoryPremium(""+rp.getPulsoryPremium());
            rv.setVechcleVesselTax(""+rp.getVechcleVesselTax());
            rv.setAllPremium(""+rp.getAllPremium());
            rv.setFollowPoint(""+rp.getFollowPoint());
            rv.setReplenishPoint(""+rp.getReplenishPoint());
            rv.setPayInsurerAmt(""+rp.getPayInsurerAmt());
            LocalDateTime cdate = rp.getCreateDate();
            LocalDateTime idate = rp.getDatePolicy();
            LocalDateTime ccdate = rp.getSurrenderDate();
            if(cdate != null){
                rv.setCreateDate((""+cdate).substring(0,10));
            }
            if(idate != null){
                rv.setDatePolicy((""+idate).substring(0,10));
            }
            if(ccdate != null){
                rv.setSurrenderDate((""+ccdate).substring(0,10));
            }
            rList.add(rv);
        }
        List<String> titles = new BeanUtils().operateBeans(new RepayingIVo(),0);
        String fileName = "保险公司退保中数据导出 " + DateUtils.dateToStr(new Date(), DateEnum.DATE_BANK_SEQ);
        XSSFWorkbook workbook = new ExcelUtil().getXlsxWorkbook(titles,rList,fileName,0);
        response.reset();
        try {
            //导出支持中文名，兼容IE、火狐
            if (request.getHeader("user-agent").indexOf("MSIE") != -1) {
                fileName = java.net.URLEncoder.encode(fileName, "utf-8") + ".xlsx";
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xlsx";
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/downloadc")
    public void exportRepaycInfo(HttpServletRequest request, HttpServletResponse response) {
        String capitalStatus = request.getParameter("capitalStatus");
        String insyrerId = request.getParameter("insyrerId");
        String ordNum = request.getParameter("ordNum");
        String channelId = request.getParameter("channelId");
        String dateIssuanceStart = request.getParameter("dateIssuanceStart");
        String dateIssuanceEnd = request.getParameter("dateIssuanceEnd");
        String surrenderDateStart = request.getParameter("surrenderDateStart");
        String surrenderDateEnd = request.getParameter("surrenderDateEnd");
        Map<String,String> map =Maps.newHashMap();
        map.put("capitalStatus",capitalStatus);
        map.put("insyrerId",insyrerId);
        map.put("ordNum",ordNum);
        map.put("channelId",channelId);
        map.put("dateIssuanceStart",dateIssuanceStart);
        map.put("dateIssuanceEnd",dateIssuanceEnd);
        map.put("surrenderDateStart",surrenderDateStart);
        map.put("surrenderDateEnd",surrenderDateEnd);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long userId =user.getTid();
        int level = user.getUserLevel();
        if(3==level){
            map.put("userId",""+userId);
        }
        List<Dictionary> dlist = iDictionaryService.getDictionaryListByType("PAY_THEME");
        List<Repaying> list = orderReapyingService.getRepayList(map);
        List<RepayingCVo> rList = Lists.newArrayList();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        for(Repaying rp:list){
            RepayingCVo rv = new RepayingCVo();
            rv.setOrdNum(rp.getOrdNum());
            for(Dictionary d:dlist){
                if(d.getRiskKey().equals(""+rp.getPaySubject())){
                    rv.setPaySubject(d.getRiskValue());
                }
            }
            rv.setInsyrerName(rp.getInsyrerName());
            if(1==rp.getChannelType()){
                rv.setChannelName(rp.getChannelPName());
            }else{
                rv.setChannelName(rp.getChannelCName());
            }
            rv.setChannelPhone(rp.getChannelPhone());
            if(1==rp.getTypeInsurance()){
                rv.setTypeInsurance("商业险");
            }else{
                rv.setTypeInsurance("交强险");
            }
            rv.setInsurant(rp.getInsurant());
            rv.setOrgIdCode(rp.getOrgIdCode());
            rv.setPlateNum(rp.getPlateNum());
            rv.setMercialPremium(""+rp.getMercialPremium());
            rv.setPulsoryPremium(""+rp.getPulsoryPremium());
            rv.setVechcleVesselTax(""+rp.getVechcleVesselTax());
            rv.setAllPremium(""+rp.getAllPremium());
            LocalDateTime sdate = rp.getDatePolicy();
            LocalDateTime cdate = rp.getSurrenderDate();
            LocalDateTime idate = rp.getDateIssuance();
            LocalDateTime mdate = rp.getInsyrerMaturityDate();
            if(sdate != null){
                rv.setDatePolicy((""+sdate).substring(0,10));
            }
            if(cdate != null){
                rv.setSurrenderDate((""+cdate).substring(0,10));
            }
            if(idate != null){
                rv.setDateIssuance((""+idate).substring(0,10));
            }
            if(mdate != null){
                rv.setInsyrerMaturityDate((""+mdate).substring(0,10));
            }
            rv.setChannelRebate(""+rp.getChannelRebate());
            rv.setInsureMustRebateAmt(""+rp.getInsureMustRebateAmt());
            rv.setInsureMustPremium(""+rp.getInsureMustPremium());
            rv.setInsureRealPremium(""+rp.getInsureRealPremium());
            rv.setMustRebateAmt(""+rp.getMustRebateAmt());
            rv.setMustPremium(""+rp.getMustPremium());
            BigDecimal re = rp.getMustRebateAmt();
            BigDecimal pe = rp.getMustPremium();
            if(re == null){
                re = new BigDecimal(0);
            }
            if(pe == null){
                pe = new BigDecimal(0);
            }
            re = re.add(pe);
            rv.setRealRebateAmt(""+re);
            rv.setSalemanName(""+rp.getSalemanName());
            rList.add(rv);
        }
        List<String> cTitles =new BeanUtils().operateBeans(new RepayingCVo(),0);
        String fileName = "保险公司退保中数据导出 " + DateUtils.dateToStr(new Date(), DateEnum.DATE_BANK_SEQ);
        XSSFWorkbook workbook = new ExcelUtil().getXlsxWorkbook(cTitles,rList,fileName,0);
        response.reset();
        try {
            //导出支持中文名，兼容IE、火狐
            if (request.getHeader("user-agent").indexOf("MSIE") != -1) {
                fileName = java.net.URLEncoder.encode(fileName, "utf-8") + ".xlsx";
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xlsx";
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
